package com.dragon.logical.service.customer.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dragon.common.model.ResultCode;
import com.dragon.common.model.exception.CustomException;
import com.dragon.common.util.StringUtils;
import com.dragon.logical.service.auth.PositionService;
import com.dragon.logical.service.customer.CustomerService;
import com.dragon.repository.config.annotation.DataScope;
import com.dragon.repository.entity.*;
import com.dragon.repository.mapper.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * <p>
 * 客户表 服务实现类
 * </p>
 *
 * @author sy
 * @since 2023-06-16
 */
@Service
public class CustomerServiceImpl extends ServiceImpl<CustomerMapper, Customer> implements CustomerService {

    @Autowired
    CustomerMapper mapper;
    @Autowired
    AdminMapper adminMapper;
    @Autowired
    AccountrecordssMapper accountMapper;
    @Autowired
    FollowMapper followMapper;
    @Autowired
    GoodsMapper goodsMapper;
    @Autowired
    ContractMapper contractMapper;
    @Autowired
    PositionService positionService;
    @Autowired
    ExamineMapper examineMapper;
    @Autowired
    DoReminderMapper doReminderMapper;
    @Autowired
    ToSendMapper toSendMapper;

    @Override
    public Page<Customer> selectCustomerList(String search,Integer status, Integer page, Integer limit, Integer applicationId, Integer settlement) {
        Page<Customer> customerPage = new Page<>(page,limit);
        QueryWrapper<Customer> wrapper = new QueryWrapper<>();
        wrapper.eq("M.deleted",0)
                .like(StringUtils.isNotBlank(search),"M.customer_name", search)
                .eq(status != null, "M.status", status)
                .eq(settlement != null, "M.settlement", settlement)
                .eq(applicationId != null, "M.admin_id", applicationId)
                .orderByDesc("M.create_time");
        return mapper.selectCustomerList(customerPage,wrapper);
    }

    @Override
    public AddPageData addCustomer(Customer customer) {
        customer.setCreateTime(DateUtil.date());

        mapper.insert(customer);

        AddPageData addPageData = new AddPageData();
        addPageData.setAdminId(customer.getAdminId());
        addPageData.setCorrelationId(customer.getId());
        addPageData.setWorkflowJson(customer.getWorkflowJsonList());
        addPageData.setStreamType(10);
        addPageData.setTitle(customer.getCustomerName());
        addPageData.setExempt(customer.getExempt());
       return addPageData;
    }



    @Override
    public void updateCustomer(Customer customer) {
        Customer cus = mapper.selectById(customer.getId());
        if (cus == null){
            throw new CustomException(ResultCode.DATA_NOT_FOUND);
        }
        customer.setUpdateTime(DateUtil.date());
        mapper.updateById(customer);
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public void deleteCustomerId(Integer id) {
        Customer customer = mapper.selectById(id);
        if (customer == null){
            throw new CustomException(ResultCode.DATA_NOT_FOUND);
        }
//        QueryWrapper<Accountrecordss> wrapper = new QueryWrapper<>();
//        wrapper.lambda().eq(Accountrecordss::getCustomerId,customer.getId());
//        Accountrecordss one = accountMapper.selectOne(wrapper);
//        if (one != null){
//            accountMapper.delete(wrapper);
//        }
        deleteThorough(10,id);
        mapper.fakeDelete(id);
    }

    @Override
    public void changeAdminId(Integer id,Integer adminId){
        Admin admin = adminMapper.selectById(adminId);
        if (admin == null){
            throw new CustomException(ResultCode.DATA_NOT_FOUND);
        }
        UpdateWrapper<Customer> adminUpdateWrapper = new UpdateWrapper<>();
        adminUpdateWrapper.lambda().eq(Customer::getId,id).set(Customer::getAdminId,adminId);
    }

    @Override
    public Page<Contract> listId(Integer customerId){
        Page<Contract> contractPage = new Page<>();
        return mapper.list(contractPage,customerId);
    }

    @Override
    public Customer selectDetailById(Integer id) {
        Customer customer = mapper.selectById(id);
        String username = adminMapper.selectUsernameById(customer.getAdminId());
        customer.setApplicantName(username);
        if (customer!= null){
            List<Goods> goods = goodsMapper.selectList(new QueryWrapper<Goods>().lambda().eq(Goods::getCustomerId, id));
            if (goods != null){
                customer.setGoodsList(goods);
            }
            //合同成交记录
            QueryWrapper<Contract> wrapper = new QueryWrapper<>();
            List<Contract> contracts = contractMapper.selectList(wrapper
                    .lambda().eq(Contract::getStatus,1).eq(Contract::getCustomerId,id));
            customer.setContractList(contracts);
        }
        // 查询跟进记录
        List<Follow> follows = followMapper.selectFollowList(id);
        if (follows == null){
            follows = new ArrayList<>();
        }
        customer.setFollowList(follows);
        //产品
        return customer;
    }

    @Override
    public Map<String,Object> newCustomerNub() {
        // 获取当前时间 转成年月
        //获取当前时间年月
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
        String time = sdf.format(new Date());

        List<Customer> customers = new ArrayList<>();
        //判断是否为管理员
        List<Customer> list = mapper.selectListByTime(time);
        Map<String, Object> map = new HashMap<>();
        map.put("Current",customers.size());
        map.put("Total",list.size());
        return map;
    }

    @Override
    public void distinctCustomerName(String name){
        Customer customers = mapper.selectOne(new QueryWrapper<Customer>()
                .lambda().eq(Customer::getCustomerName,name).eq(Customer::getDeleted,0));
        if (customers != null){
            Admin admin = adminMapper.selectById(customers.getAdminId());
            String message = "";
            if(admin!= null){
                message = "该客户已添加，添加人:".concat(admin.getUsername());
            } else {
                message = "该客户已添加，添加人不存在";
            }
            throw new CustomException(ResultCode.DATA_ALREADY_EXISTS.code(),message);
        }
    }

    @Override
    public void updateAdminId(Integer id, Integer adminId){
        Customer customer = mapper.selectById(id);
        if (customer == null){
            throw new CustomException(ResultCode.DATA_NOT_FOUND);
        }
        customer.setAdminId(adminId);
        customer.setUpdateTime(DateUtil.date());
        mapper.updateById(customer);
    }

    @Override
    @DataScope(deptAlias = "",deptField = "department_id",adminAlias = "",adminField = "admin_id")
    public List<Customer> listByAdminId(Integer adminId, String search) {
        List<Customer> customerList = mapper.selectList(new QueryWrapper<Customer>()
                .lambda()
                .eq(Customer::getDeleted,0).like(StrUtil.isNotBlank(search),Customer::getCustomerName,search));
        return customerList;
    }

    @Override
    public void deleteThorough(Integer streamType, Integer correlationId){
        //审批表
        examineMapper.delete(new QueryWrapper<Examine>().lambda()
                .eq(Examine::getStreamType, streamType).eq(Examine::getCorrelationId, correlationId));
        //to_send
        toSendMapper.delete(new QueryWrapper<ToSend>().lambda()
                .eq(ToSend::getStreamType, streamType).eq(ToSend::getCorrelationId,correlationId));
        //do_reminder
        doReminderMapper.delete(new QueryWrapper<DoReminder>().lambda()
                .eq(DoReminder::getOperationType, streamType).eq(DoReminder::getCorrlelationId, correlationId));
    }

    @Override
    public void antiAudit(Integer correlationId){
        Customer customer = mapper.selectById(correlationId);
        customer.setStatus(0);
        mapper.updateById(customer);
    }

    @Override
    public Customer selectDetailByContractId(Integer contractId) {
        Contract contract = contractMapper.selectById(contractId);
        Customer customer = mapper.selectDetailById(contract.getCustomerId());
        return customer;
    }


    @Override
    public void upgradeSettlement(Integer id){
        Customer customer = mapper.selectById(id);
        if (customer == null){
            throw new CustomException(ResultCode.DATA_NOT_FOUND);
        }
        customer.setSettlement(2);
        customer.setUpdateTime(DateUtil.date());
        mapper.updateById(customer);
    }

    @Override
    public Page<Customer> selectCountContractBy(String name,String startTime,String endTime,Integer page,Integer limit){
        Page<Customer> customerPage = new Page<>(page,limit);
        QueryWrapper<Customer> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("a.status",1)
                .eq("a.deleted",0)
                .like(StrUtil.isNotBlank(name),"b.customer_name",name)
                .eq("b.status",1)
                .eq("b.deleted",0);
        if(StrUtil.isNotBlank(startTime)){
            queryWrapper.ge("a.order_time",DateUtil.parse(startTime,"yyyy-MM-dd"));
        }
        if(StrUtil.isNotBlank(endTime)){
            queryWrapper.le("a.order_time",DateUtil.parse(endTime,"yyyy-MM-dd"));
        }
        Page<Customer> customerPage1 = mapper.selectCountContractBy(customerPage,queryWrapper);
        return customerPage1;
    }

    @Override
    public Page<Customer> selectCountCustomerByYearMonth(String name,String startTime,String endTime,Integer page,Integer limit){
        Page<Customer> customerPage = new Page<>(page,limit);
        QueryWrapper<Customer> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("a.status",1)
                .eq("a.deleted",0)
                .like(StrUtil.isNotBlank(name),"b.customer_name",name)
                .eq("b.status",1)
                .eq("b.deleted",0);
        if(StrUtil.isNotBlank(startTime)){
            queryWrapper.ge("a.order_time",DateUtil.parse(startTime,"yyyy-MM-dd"));
        }
        if(StrUtil.isNotBlank(endTime)){
            queryWrapper.le("a.order_time",DateUtil.parse(endTime,"yyyy-MM-dd"));
        }
        Page<Customer> customerPage1 = mapper.selectCountContractBy(customerPage,queryWrapper);
        return customerPage1;
    }
}
